package backTracing;

import java.util.*;

public class 全排列II {

    public static void main(String[] args) {
        List<List<Integer>> lists = permuteUnique(new int[]{1, 1, 2});
        for (List<Integer> integers : lists) {
            System.out.println(integers);
        }
    }

    static List<List<Integer>> res = new ArrayList<>();
    static LinkedList<Integer> list = new LinkedList<>();
    static HashMap<Integer, HashSet<Integer>> map = new HashMap<>();
    static boolean[] flag;

    public static List<List<Integer>> permuteUnique(int[] nums) {
        //递归去重
        flag = new boolean[nums.length];
        backTracking(nums, flag, map, 1);
        return res;
    }

    public static void backTracking(int[] nums, boolean[] flag, HashMap<Integer, HashSet<Integer>> map, int floor) {
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (list.size() == nums.length) {
                res.add(new ArrayList(list));
                return;
            }
            if (flag[i] == true || (map.get(floor) != null && map.get(floor).contains(nums[i])))
                continue;
            //层数
            set.add(nums[i]);
            map.put(floor, set);
            list.add(nums[i]);
            flag[i] = true;
            backTracking(nums, flag, map, floor + 1);
            flag[i] = false;
            list.removeLast();
        }
        set.clear();
    }
}
